package org.redmagic.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

public final class Hierarchies {

    public static List<String> toHierarchies(List<List<String>> attempts) {
        List<String> hierarchy = new ArrayList<String>();
        for (List<String> attempt : attempts) {
            hierarchy.add(createTagsString(attempt));
        }
        return hierarchy;
    }

    public static String createTagsString(List<String> attempt) {
        TreeSet<String> singleTags = new TreeSet<String>();
        TreeSet<String> nonSingleTags = new TreeSet<String>();
        for (String tag : attempt) {
            if (tag.contains("=")) {
                nonSingleTags.add(tag);
            } else if (!tag.isEmpty()) {
                singleTags.add(tag);
            }
        }
        return assemble(singleTags, nonSingleTags);
    }

    private static String assemble(TreeSet<String> singleTags, TreeSet<String> nonSingleTags) {
        String convertedSingleTags = assembleSingleTags(singleTags);
        if (convertedSingleTags != null) {
            nonSingleTags.add(convertedSingleTags);            
        }
        return combineWithSeparator(nonSingleTags, "&");
    }

    private static String assembleSingleTags(TreeSet<String> singleTags) {
        if (!singleTags.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            sb.append("tags=");
            sb.append(combineWithSeparator(singleTags, ","));
            return sb.toString();            
        } else {
            return null;
        }
    }
    
    private static String combineWithSeparator(TreeSet<String> orderedSet, String separator) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iter = orderedSet.iterator();
        while (iter.hasNext()) {
            sb.append(iter.next());
            if (iter.hasNext()) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }
}